﻿using System;
using System.Linq.Expressions;

namespace Sapphire.Linq.Framework
{
    public static class TypesHelper
    {
        public static bool IsCount(this Expression expression)
        {
            if (expression is MethodCallExpression)
                return ((MethodCallExpression)expression).Method.Name == "Count";

            return false;
        }

        public static bool IsEmptyCount(this Expression expression)
        {
            if (expression is MethodCallExpression)
                return IsCount(expression) && ((MethodCallExpression)(expression)).Arguments.Count == 1;

            return false;
        }

        public static bool IsSkip(this Expression expression)
        {
            return expression.ToString().Contains(".Skip(");
        }

        public static Type GetEntityType(Type type)
        {
            if (type.IsGenericType)
            {
                var resultType = type.GetGenericArguments()[0];

                if (resultType.Name.StartsWith("IGrouping"))
                    return type.GetGenericArguments()[0].GetGenericArguments()[1];

                return resultType;
            }

            return type;
        }

        public static Type GetEntityType(Expression expression)
        {
            var type = GetEntityType(expression.Type);

            if (type == typeof(int))
            {
                var el = (((MethodCallExpression)expression).Arguments)[0];
                return GetEntityType(el.Type);
            }

            return type;
        }
    }
}